<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use App\Models\Category;

use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Tree;
use Encore\Admin\Facades\Admin;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Request;

class CategoryController extends Controller
{
    use ModelForm;
    // 照片类别
    const TYPE_PHOTO = 1;
    /**
     * Current type.
     *
     * @var int
     */
    protected static $_type = self::TYPE_PHOTO;

    // 分类类别选项
    protected $types = [];

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $this->init();
        return Admin::content(function (Content $content) {
            $content->header('分类');
            $content->body(Category::tree(function ($tree) {
                $tree->query(function ($model) {
                    return $model->where('type', static::$_type);
                });
            }));
        });
    }

    /**
     * Show interface.
     *
     * @param mixed   $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed   $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('Edit')
            ->description('description')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('Create')
            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Category);

        $grid->id('ID')->sortable();
        $grid->created_at('Created at');
        $grid->updated_at('Updated at');

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Category::findOrFail($id));

        $show->id('ID');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $this->init();
        $form = new Form(new Category);

        $form->display('id', 'ID');
        $form->select('type', '类别')->options($this->types)->rules('required'); 
        $type = static::$_type;
        $form->text('name', '标题')->rules(function ($form)use($type) {
            // 如果不是编辑状态，则添加字段唯一验证
            if (!$id = $form->model()->id) {
                // return ['required','unique:categories'];
                return [
                    'required',
                    function($attribute, $value, $fail)use($type) {
                        $category = Category::where('type', $type)
                               ->where('name',$value)
                               ->get()
                               ->pluck('id')
                               ->all();
                        if($category){
                            return $fail($attribute.' 不能重复.');
                        }
                    },
                ];
            }
            return ['required'];
        }); 
        $form->text('sort', '排序')->rules('required'); 

        $form->select('pid', '上级ID')->options(Category::selectOptions(function ($query) {
            return $query->where('type', static::$_type);
        }));
        $form->display('created_at', 'Created At');
        $form->display('updated_at', 'Updated At');
        $form->saved(function (Form $form) {
            return redirect()->route('category.index', ['type'=>static::$_type]);
        });


        Admin::script($this->script());

        return $form;
    }
    /**
     * @author liud 2018-12-06
     * @copyright [初始化]
     * @license   [license]
     * @version   [version]
     * @return    [type]      [description]
     */
    protected function init(){
        // 获取配置类别数组
        $this->types   = config('admin.category_types');
        // 根据表单设置分类类别
        $type          = request()->get('type');
        static::$_type = $type?$type:self::TYPE_PHOTO;
    }
    protected function script()
    {
        $url  = Request::fullUrlWithQuery(['type' => '_type_']);
        $type = static::$_type;

        return <<<EOT
// 根据url-type设置默认值
var type = "$type";
if(type){
    $('.type').val([type]);
}
$(".type").on("change",function (e) {
    e.preventDefault();

    var url = "$url".replace('_type_', $(this).val());
    console.log(url);

    $.pjax({container:'#pjax-container', url: url });

});

EOT;
    }
    // 获取热搜词语
    public function getHotWords(){
        return json_encode(Category::all()->pluck('name')->take(10));
    }
}
